Page({
  data: {
    backendUrl: 'http://127.0.0.1:88/api/user/',
    coach: null,
    dateList: [],
    currentDate: '',
    timeSlots: [
      '09:00-10:00', '10:00-11:00', '11:00-12:00', 
      '14:00-15:00', '15:00-16:00', '16:00-17:00',
      '17:00-18:00', '18:00-19:00', '19:00-20:00'
    ],
    selectedTime: '',
    availableSlots: [],
    userInfo: null,
    canSubmit: false,
    coachId: null
  },

  onLoad(options) {
    const { id, date } = options;
    const userInfo = wx.getStorageSync('userInfo');
    if (!userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500
      });
      setTimeout(() => {
        wx.navigateTo({
          url: '/pages/login/login'
        });
      }, 1500);
      return;
    }

    this.setData({
      userInfo,
      currentDate: date || this.formatFullDate(new Date()),
      coachId: id
    });
    
    if (id) {
      this.loadCoachDetail(id);
    }
    this.initDateList();
  },

  // 初始化日期列表
  initDateList() {
    const dateList = [];
    const days = ['日', '一', '二', '三', '四', '五', '六'];
    const today = new Date();
    
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(today.getDate() + i);
      
      let dayText = i === 0 ? '今日' : 
                   i === 1 ? '明日' : 
                   '周' + days[date.getDay()];
      
      dateList.push({
        fullDate: this.formatFullDate(date),
        day: date.getDate(),
        weekday: dayText
      });
    }

    this.setData({ dateList });
  },

  // 格式化日期
  formatFullDate(date) {
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  // 加载教练详情
  loadCoachDetail(id) {
    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    wx.request({
      url: this.data.backendUrl + 'coach_booking.php',
      data: { 
        action: 'get_coach_detail',
        id 
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            coach: res.data.coach
          });
          this.loadAvailableSlots();
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // 加载可用时间段
  loadAvailableSlots() {
    if (!this.data.coachId) return;

    wx.request({
      url: this.data.backendUrl + 'coach_booking.php',
      data: {
        action: 'get_available_slots',
        coach_id: this.data.coachId,
        date: this.data.currentDate
      },
      header: {
        'content-type': 'application/json'
      },
      success: (res) => {
        if (res.data.status === 'success') {
          this.setData({
            timeSlots: res.data.slots || [],
            selectedTime: '',
            canSubmit: false
          });
        }
      }
    });
  },

  // 选择日期
  selectDate(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({ 
      currentDate: date,
      selectedTime: '',
      canSubmit: false
    });
    this.loadAvailableSlots();
  },

  // 选择时间
  selectTime(e) {
    const time = e.currentTarget.dataset.time;
    const status = e.currentTarget.dataset.status;
    
    if (status === 'available') {
      this.setData({ 
        selectedTime: time,
        canSubmit: true
      });
    }
  },

  // 提交预约
  submitBooking() {
    if (!this.data.canSubmit) return;
    const requestData = {
        action: 'create_booking',
        user_id: this.data.userInfo.id,
        coach_id: this.data.coachId,
        type: 1,
        booking_date: this.data.currentDate,
        time_slot: this.data.selectedTime
    };
    wx.showLoading({
        title: '预约中...',
        mask: true
    });
    wx.request({
        url: this.data.backendUrl + 'coach_booking.php',
        method: 'POST',
        header: {
            'content-type': 'application/x-www-form-urlencoded'
        },
        data: requestData,
        success: (res) => {
            wx.hideLoading();
            
            if (res.data && res.data.status === 'success') {
                wx.showToast({
                    title: '预约成功',
                    icon: 'success',
                    duration: 2000
                });
                setTimeout(() => {
                    wx.redirectTo({
                        url: '/pages/my-bookings/my-bookings'
                    });
                }, 2000);
            } else {
                wx.showToast({
                    title: res.data ? res.data.message : '预约失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
        fail: () => {
            wx.hideLoading();
            wx.showToast({
                title: '网络错误',
                icon: 'none',
                duration: 2000
            });
        }
    });
  }
}); 